module ActsCrummy #:nodoc:

  # This module is mixed into ActionView::Base to provide the ability to render
  # breadcrumbs using the structure from the models.

  module BreadcrumbsHelper
    DEFAULT_BREADCRUMB_SEPARATOR = ' &gt; '
    # Renders breadcrumbs up the model hierarchy starting with <tt>child</tt>,
    # creating a link for each item, and returning the result as a string.  It
    # works by selecting the return value of the method parent from each
    # model object.  Each parent value is expected to be an instance of a
    # model so that a link can be rendered.  As a convenience, the method
    # ActiveRecord::Base.is_child_to is provided so that the existing model
    # does not need to be altered to use breadcrumbs.
    #
    # The only allowable currently is <tt>:level</tt>, which is an optional
    # integer to limit the number of parent links displayed to.

    def render_breadcrumbs child, options = {}
      i, level = 0, (options[:level] || -1)
      urls = [describe_model(child)]
      parent = child

      while parent.respond_to?(:parent) && i != level && (parent = parent.parent)
        i += 1
        # if block_given?
        urls.unshift(parent_link(parent, options))
        # else
        #   urls.unshift(parent_link(parent))
        # end          
      end

      urls.join(options[:separator] || DEFAULT_BREADCRUMB_SEPARATOR)
    end

    private
    def parent_link parent, options = {}
      link_to describe_model(parent), parent
    end

    def describe_model model
      model.respond_to?(:name) ? "#{model.class} #{model.name}" : model.class.to_s
    end
  end
end
